package edu.upc.clase.demo.dao.impl;

import edu.upc.clase.demo.dao.ReservaDao;
import edu.upc.clase.demo.entity.Reserva;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class ReservaDaoImpl extends SimpleJdbcDaoSupport implements ReservaDao{
    
     private static Logger log = LoggerFactory.getLogger(ReservaDaoImpl.class);

    @Autowired
    public ReservaDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }
    
    @Override
    public Integer insertar(Reserva reserva) {
        getJdbcTemplate().update(
                "insert into reserva (codigousuario,codigosala,fecha,hora) values (?, ?, ?, ?)",
                reserva.getCodigoUsuario(), reserva.getCodigoSala(), reserva.getFecha(),reserva.getHora());
        return getSimpleJdbcTemplate().queryForInt("select last_insert_id()");
    }
    
    @Override
    public void actualizar(Reserva reserva) {
        getJdbcTemplate().update(
                "update reserva set hora = ? where codigoreserva = ?",
                 reserva.getHora(), reserva.getCodigoReserva());
    }
    
    @Override
    public void eliminar(Reserva reserva) {
        getJdbcTemplate().update(
                "delete from reserva where codigoreserva = ?", reserva.getCodigoReserva());
    }
    
    @Override
    public Reserva buscar(Integer id) {
        try {
            return getSimpleJdbcTemplate().queryForObject(
                    "select codigoreserva,codigousuario,codigosala,fecha,hora from reserva where codigoreserva=?",
                    new BeanPropertyRowMapper<Reserva>(Reserva.class), id);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    @Override
    public List<Reserva> buscarTodos() {
        return getSimpleJdbcTemplate().query(
                "select codigoreserva,codigousuario,codigosala,fecha,hora from reserva",
                new BeanPropertyRowMapper<Reserva>(Reserva.class));
    }
    
    
}
